#!/bin/bash

### BEGIN INIT INFO
# Provides:          piaware
# Required-Start:    $network $remote_fs $syslog $time
# Required-Stop:     $network $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Communicate ADS-B data to FlightAware
# Description:       piaware is a way to connect a homebrew Raspberry Pi-based
#                    ADS-B receiver running dump1090 over a TLS connection to
#                    forward ADS-B data to FlightAware
### END INIT INFO

. /lib/lsb/init-functions

DAEMON=/usr/bin/piaware
RUNDIR=/run/piaware
PIDFILE=$RUNDIR/piaware.pid
STATUSFILE=$RUNDIR/status.json
LOGFILE=/var/log/piaware.log
RUNAS=piaware

test -x $DAEMON || exit 5

start() {
    log_daemon_msg "Starting piaware server" "piaware"

    # ensure the logfile exists with the right ownership
    # so piaware can modify it
    touch $LOGFILE
    chown $RUNAS $LOGFILE
    chmod u+rw $LOGFILE

    # create $RUNDIR for $STATUSFILE, $PIDFILE
    mkdir -p $RUNDIR
    chown $RUNAS $RUNDIR
    chmod 0755 $RUNDIR

    # make sure we have a pirehose cert
    /usr/lib/pirehose/generate-cert.sh

    /sbin/start-stop-daemon --start --oknodo --background --user $RUNAS --pidfile $PIDFILE --chuid $RUNAS --exec $DAEMON -- -p $PIDFILE -logfile $LOGFILE -statusfile $STATUSFILE
    status=$?
    log_end_msg $status
    return
}

stop() {
    log_daemon_msg "Stopping piaware server" "piaware"
    /sbin/start-stop-daemon --stop --quiet --oknodo --user $RUNAS --pidfile $PIDFILE --exec $DAEMON --retry 5
    log_end_msg $?
    rm -f $PIDFILE
    return
}

reload() {
    log_daemon_msg "Reloading piaware server configuration" "piaware"
    /sbin/start-stop-daemon --stop --quiet --oknodo --user $RUNAS --pidfile $PIDFILE --exec $DAEMON --signal HUP
    log_end_msg $?
    return
}

rotate() {
    log_daemon_msg "Rotating piaware server logfiles" "piaware"
    /sbin/start-stop-daemon --stop --quiet --oknodo --user $RUNAS --pidfile $PIDFILE --exec $DAEMON --signal USR1
    log_end_msg $?
    return
}

status() {
	/usr/bin/piaware-config -status
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
	status
        ;;
    restart)
        stop && sleep 2 && start
        ;;
    reload|force-reload)
        reload
	;;
    rotate)
        rotate
	;;
    status)
	status_of_proc $DAEMON "piaware server"
	;;
    *)
	echo "Usage: $0 {start|stop|restart|reload|force-reload|rotate|status}"
	exit 2
	;;
esac
